import axios, {
  AxiosInstance,
  AxiosRequestConfig,
  AxiosPromise,
  AxiosResponse,
} from "axios";

const ENV: ImportMetaEnv = import.meta.env;
import config from "@/config/";

const apiBaseUrl =
  ENV.MODE === "beta"
    ? config.beta.baseUrl
    : ENV.MODE === "development"
    ? config.development.baseUrl
    : config.release.baseUrl;

class HttpRequest {
  // 构造函数
  constructor(public baseUrl: string = apiBaseUrl) {
    this.baseUrl = baseUrl;
  }

  // 合并配置
  private mergeConfig(options: AxiosRequestConfig): AxiosRequestConfig {
    return Object.assign({ baseURL: this.baseUrl }, options);
  }

  // 拦截请求
  private interceptors(instance: AxiosInstance, url?: string) {
    // 请求拦截
    instance.interceptors.request.use(
      (config: AxiosRequestConfig) => {
        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );
    // 返回拦截
    instance.interceptors.response.use(
      (res: AxiosResponse) => {
        return res;
      },
      (error) => {
        return Promise.reject(error);
      }
    );
  }

  // 发送请求
  public request(options: AxiosRequestConfig): AxiosPromise {
    const instance: AxiosInstance = axios.create();
    options = this.mergeConfig(options);
    this.interceptors(instance, options.url);
    return instance(options);
  }
}

export interface ResponseData {
  code: number;
  data?: any;
  msg: string;
}

export default HttpRequest;
